const anchor = require("@coral-xyz/anchor");
const {    ComputeBudgetProgram, PublicKey} = require("@solana/web3.js");
const getKeypair  = require('./wallet');
const config = require('./config');

const {findProgramAddress } = require('./utils');

class CpiAppProgram {
    constructor(nodeUrl) {
        this.nodeUrl = nodeUrl;
        this.keypair = getKeypair();
        this.wallet = new anchor.Wallet(this.keypair);
        this.connection = new anchor.web3.Connection(nodeUrl);

        this.provider = new anchor.AnchorProvider(this.connection,this.wallet, 'recent');
        this.program = new anchor.Program(config.cpiAppIdl, this.provider);
    }

    async outboundCall(network_id,contract_address, functionCallData) {

        let authAccount = findProgramAddress("outbound_call",this.program.programId,[]);
        let bump = authAccount.bump;
        let authPk = authAccount.publicKey;

        console.log('authPk: ',authPk);
        console.log('bump: ',bump);


        let instruction = await this.program.methods.callOutbound(network_id, contract_address, functionCallData, bump).accounts({
            messageGateProgram:new PublicKey(config.programId),
            authorityPda:authPk,
        }).instruction();
        let instructions = [
            instruction
        ];
        let tx = new anchor.web3.Transaction();
        tx.add(...instructions);

        let txHash = null;
        try{
            txHash = await this.connection.sendTransaction(tx, [this.keypair]);
            console.log('txHash: ',txHash);
        }catch (error) {
            console.log('error: ',error);
        }


    }

}

module.exports = CpiAppProgram;